﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace LD.Host.项目
{
    public static class ScrewDB
    {
        public static string[] SlotIds { get; set; } = new string[4];
        private static object lockId = new object();
        public static string NewId
        {
            get
            {
                lock (lockId)
                {
                    return Guid.NewGuid().ToString();
                }
            }
        }
        public static void MainTable(short el, TB_ScrewData data, List<short> chn1, List<short> chn2, bool last)
        {
            #region 确保目录的存在
            string directoryPath = "D:\\ScrewData"; //目录路径
            if (!Directory.Exists(directoryPath))
                Directory.CreateDirectory(directoryPath);

            #endregion
            //已有的数据需要清除
            var isExist = DBHelper.Instance.Sql.Queryable<TB_ScrewData>()
                                .Where(p => p.SN == data.SN && p.Num == data.Num && !p.IsCsv).ToList();
            isExist.ForEach((item) =>
            {
                item.IsCsv = true;
            });
            DBHelper.Instance.Sql.Updateable(isExist).ExecuteCommand();

            int id = DBHelper.Instance.Sql.Insertable(data).ExecuteReturnIdentity();

            Acup_DB(el, id, chn1, chn2);

            ScrewActioToCSV(directoryPath, id, data.SN, data.Num, last);

        }
        /// <summary>
        /// 生成CSV
        /// </summary>
        /// <remarks>
        /// 获取生成CSV数据的逻辑:
        /// 1.查找条码打钉最后时间，获取GroupId
        /// 2.根据GroupId获取OK的数据，此数据如有多个，以最早的时间为准
        /// 3.以上逻辑的修改是在重打功能上修改的
        /// </remarks>
        /// <param name="barcode">条码</param>
        /// <param name="last">是否最后一颗螺丝</param>
        public static void Screw_CSV(string barcode, bool last)
        {
            string directoryPath = "D:\\ScrewData";
            /*
             * 以下获取csv数据
             */
            //var screwList = DBHelper.Instance.Sql.Queryable<TB_ScrewData>()
            //        .Where(p => p.SN == barcode).OrderBy(p => p.Num).ToList();
            /*
             * 针对以上修改 yte 2023.12.25 车间修改
             * 修改逻辑参照Remark
             */
            var m_group = DBHelper.Instance.Sql.Queryable<TB_ScrewData>()
                                .Where(p => p.SN == barcode)
                                .OrderByDescending(p => p.CreateTime).First();

            var tempData = DBHelper.Instance.Sql.Queryable<TB_ScrewData>()
                                .Where(p => p.SN == barcode && p.GroupId == m_group.GroupId)
                                .OrderBy(p => p.CreateTime)
                                .ToList();
            /*重复项，用最新的数据
             */
            var screwList = new List<TB_ScrewData>();
            foreach (var item in tempData)
            {
                var isExist = screwList.Where(p => p.Num == item.Num).FirstOrDefault();
                if (isExist != null)
                    screwList.Remove(isExist);

                screwList.Add(item);
            }
            if (screwList.Count() > 0)
            {
                //csv
                var screwstring = new List<string>
                {
                    // 添加表头数据
                    "Order,ProductID,Task,Time,Rounds(r),Torque(Kgf.cm),TimeConsuming(ms),State,Alarm,Channel,Floating,SpeedMax,SpeedState,TorqueState"
                };

                //将所有对象中的字段拼接成csv样式
                screwstring.AddRange(screwList.Select(item => string.Join(",",
                                 item.Num,
                                 item.SN,
                                 item.TaskId,
                                 item.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"),
                                 item.Rounds,
                                 item.Torque,
                                 item.TimeConsuming,
                                 item.Result_State,
                                 item.Alarm_State,
                                 "BackY2",
                                 "0",
                                 item.SpeedFeedback,
                                 "Normal",
                                 item.Alarm_State
                             )));
                screwstring.Add(screwList.Where(p => p.Result_State == "NG")?.FirstOrDefault()?.Result_State == "NG" ? "Result,FAIL" : "Result,PASS");

                string csvString = string.Join(Environment.NewLine, screwstring);
                string filePath = Path.Combine(directoryPath, $"{barcode}.csv");

                File.WriteAllText(filePath, csvString, System.Text.Encoding.UTF8);

                if (last)
                {
                    DBHelper.Instance.Sql.Updateable<TB_ScrewData>()
                                      .Where(p => p.SN == barcode && !p.IsCsv)
                                      .SetColumns(p => p.IsCsv == true).ExecuteCommand();
                }
            }
        }
        private static void ScrewActioToCSV(string directoryPath, int pid, string barcode, int num, bool last)
        {
            try
            {
                //csv
                #region 总螺丝数据csv
                Screw_CSV(barcode, last);
                #endregion

                #region 单穴位csv
                Acup_CSV(directoryPath, pid, barcode, num);


                #endregion
            }
            catch (Exception ex)
            {
                Log4.Warr("Csv生产失败" + ex);
            }
        }
        private static void Acup_CSV(string directoryPath, int pid, string barcode, int num)
        {
            var chnList = DBHelper.Instance.Sql.Queryable<TB_ScrewDetailData>()
                   .Where(p => p.Pid == pid).ToList();

            if (chnList.Count() > 0)
            {
                var chn = new List<string>
                {
                    // 添加表头数据
                    "DeviceType,DPLUS-L-amazon",
                    $"CHN1,SpeedFeedback(rpm),{chnList.Max(p=>p.Chn1)}",
                    $"CHN2,Torque(Kgf.cm),{chnList.Max(p=>p.Chn2)}",
                    $"ReceivePoints,{chnList.Count}",
                    "SampleInterval,3",
                    "Time(ms),CHN1,CHN2"
                };
                //将所有对象中的字段拼接成csv样式
                chn.AddRange(chnList.Select(item => string.Join(",",
                               item.Times,
                               item.Chn1,
                               item.Chn2.ToString()
                           )));
                string filePath = Path.Combine(directoryPath, $"{barcode}_{num}.csv");
                string csvString = string.Join(Environment.NewLine, chn);
                File.WriteAllText(filePath, csvString, System.Text.Encoding.UTF8);
            }
        }
        private static void Acup_DB(short el, int pid, List<short> chn1, List<short> chn2)
        {
            var detail = new List<TB_ScrewDetailData>();
            int times = 0;
            for (int i = 0; i < chn2.Count; i++)
            {
                detail.Add(new TB_ScrewDetailData()
                {
                    Pid = pid,
                    Times = times,
                    Chn1 = chn1[i],
                    Chn2 = Math.Round(chn2[i] * 0.01, 3)
                }); ;
                times += Convert.ToInt32(el) / 1000;
            }
            //单穴位数据写入库中
            DBHelper.Instance.Sql.Insertable(detail).ExecuteCommand();
        }
    }

}
